package cn.xingzhe.monster.user.infrastructure.repository.impl;

import cn.xingzhe.monster.user.domain.model.UserModel;
import cn.xingzhe.monster.user.domain.repository.UserRepository;
import cn.xingzhe.monster.user.infrastructure.persistence.converter.UserEntityConverter;
import cn.xingzhe.monster.user.infrastructure.persistence.entity.UserEntity;
import cn.xingzhe.monster.user.infrastructure.repository.UserMongoRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * MongoDB 用户仓储实现
 * 内部操作 UserEntity，对外返回 UserModel
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class MongoUserRepository implements UserRepository {

    private final UserMongoRepository mongoRepository;

    public MongoUserRepository(UserMongoRepository mongoRepository) {
        this.mongoRepository = mongoRepository;
    }

    @Override
    public Optional<UserModel> findById(String id) {
        return mongoRepository.findById(id)
                .map(UserEntityConverter::toModel);
    }

    @Override
    public Optional<UserModel> findByUsername(String username) {
        return mongoRepository.findByUsername(username)
                .map(UserEntityConverter::toModel);
    }

    @Override
    public Optional<UserModel> findByEmail(String email) {
        return mongoRepository.findByEmail(email)
                .map(UserEntityConverter::toModel);
    }

    @Override
    public Optional<UserModel> findByPhone(String phone) {
        return mongoRepository.findByPhone(phone)
                .map(UserEntityConverter::toModel);
    }

    @Override
    public boolean existsByUsername(String username) {
        return mongoRepository.existsByUsername(username);
    }

    @Override
    public boolean existsByEmail(String email) {
        return mongoRepository.existsByEmail(email);
    }

    @Override
    public boolean existsByPhone(String phone) {
        return mongoRepository.existsByPhone(phone);
    }

    @Override
    public UserModel save(UserModel user) {
        UserEntity entity = UserEntityConverter.toEntity(user);
        UserEntity savedEntity = mongoRepository.save(entity);
        return UserEntityConverter.toModel(savedEntity);
    }

    @Override
    public List<UserModel> findByIds(List<String> ids) {
        List<UserEntity> entities = mongoRepository.findAllById(ids);
        return entities.stream()
                .map(UserEntityConverter::toModel)
                .collect(Collectors.toList());
    }

    @Override
    public void deleteById(String id) {
        mongoRepository.deleteById(id);
    }

}

